package com.yj.idempotence.dao;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Component
@Slf4j
public class TokenImpl implements ITokenDao {

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public String createToken() {

        String token = UUID.randomUUID().toString();
        token.replace(" ","-");
//        StringBuilder token = new StringBuilder();
//        token.append("LOGIN").append(s);

//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.opsForValue().set(token,token,1000000);

        log.info("获取到了token：{}",token);


        if (!StringUtils.isEmpty(token)){
            return token;
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) {

        // 1.先判断header 是否包含token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)){
                throw new RuntimeException("违规请求！");
            }
        }
        if (!redisTemplate.hasKey(token)){
            throw new RuntimeException("违规请求");
        }
        Boolean delete = redisTemplate.delete(token);
        if (!delete){
            throw new RuntimeException("删除token key失败！");
        }
        return true;
    }
}
